<template>
    <!--  -->
    <el-card :body-style="{ height: '80vh' }">
        <!-- 搜索条件 -->
        <div class="main-top">
            <div class="main-middle">
                <el-form :model="seaForm">
                    <!-- 第一行 -->
                    <span>任务标题：</span>
                    <el-input v-model="seaForm.title" />
                    <span>任务状态：</span>
                    <el-select v-model="seaForm.state" class="m-1" placeholder="请选择">
                        <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value01" />
                    </el-select>
                    <span>工作分类：</span>
                    <el-select v-model="seaForm.classify" class="m-2" placeholder="请选择">
                        <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value02" />
                    </el-select>
                    <span>优先级：</span>
                    <el-select v-model="seaForm.priority" class="m-3" placeholder="请选择">
                        <el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value03" />
                    </el-select>
                    <br />
                    <br />
                    <!-- 第二行 -->
                    <el-config-provider :locale="locale">
                        <span>截止日期：</span>
                        <el-date-picker v-model="seaForm.time_range" type="datetimerange" format="YYYY/MM/DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss" :default-time="defaultTime" range-separator="至" />
                    </el-config-provider>
                    <!-- <span>执行人：</span>
            <el-input v-model="seaForm.executed" /> -->
                    <div class="right">
                        <el-button class="search" type="primary" icon="Search" size="small" @click="onSubmit">搜索</el-button>
                        <el-button class="reset" type="primary" icon="RefreshRight" size="small"
                            @click="onReset">重置</el-button>
                    </div>
                </el-form>
            </div>

            <br />
            <hr style="background-color: #5aa2cc; height: 1px; border: none" />
            <!-- 新增任务 -->
            <div>
                <el-button type="primary" @click="handleAdd" class="add" size="small">新增任务</el-button>
                <!-- 弹窗子组件 -->
                <myDialog :dataForm='dataForm' :dialogOpen="dialogOpen" :modalTypes="modalTypes" :taskTitle="taskTitle"
                    :imageUrl="imageUrl" @submitSure="submitSure" @changeAcademic="changeAcademic"
                    @submitClose="submitClose" @resetForm="resetForm"></myDialog>
            </div>
            <hr style="background-color: #e8e8e8; height: 2px; border: none" />
        </div>
        <!-- 表格 -->
        <div class="common-table">
            <!-- height="50vh" -->
            <el-table :data="tableData" stripe style="width: 100%">
                <!-- <el-table-column v-for="(item, index) in tableTitle" :prop="item.props" :label="item.label" :key="index" /> -->
                <el-table-column prop="id" label="任务编号" :key="index" min-width="15%" />
                <el-table-column prop="title" label="任务标题" :key="index" min-width="10%" />
                <el-table-column prop="classify" label="工作分类" :key="index" min-width="8%" />
                <el-table-column prop="priority" label="优先级" :key="index" min-width="10%" />
                <el-table-column prop="createName" label="创建人" :key="index" min-width="10%" />
                <el-table-column prop="executors" label="执行人" :key="index" min-width="12%" />
                <el-table-column prop="deadline" label="截止日期" :key="index" min-width="15%" />
                <el-table-column prop="state" label="状态" :key="index" min-width="10%" />
                <el-table-column fixed="right" label="操作" width="140" min-width="10%">
                    <template #default="{ row }">
                        <el-button link type="primary" size="small" @click="handleDetail(row)">查看</el-button>
                        <el-button link type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                        <el-button link type="primary" size="small" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pager">
                <el-pagination :page-size="pageData.page_size" :pager-count="5" layout="prev, pager, next"
                    :page-count="total" @update:current-page="handlePage" />
            </div>
        </div>
    </el-card>
</template>
  
<script setup>
import myDialog from './myDialog.vue'
import locale from 'element-plus/lib/locale/lang/zh-cn'; // 中文语言
import { getTask, delTask, getCascade, taskDetail, addTask, editTask } from '../../api/index'
import { useList } from '../../store/index'
import { regroupData } from '../../utils/system/regroupData' //regroupData
import { nextTick } from 'vue';

const router = useRouter();

//引入pinia tableDataL任务列表数据
const store = useList()

//分页数据
const pageData = reactive({
    start_number: 1, //默认页码为1
    page_size: 8, //默认一页显示8条
})
const total = ref()   //表示数据的总条数
//搜索表单数据
let seaForm = reactive({
    title: '',
    state: '',
    classify: '', //任务状态
    priority: '',
    time_range: '',
    executed: '',
})
const defaultTime = new Date(2000, 1, 1, 12, 0, 0)

const dialogOpen = ref(false)
const modalTypes = ref(false) // true表示新增的浮窗 false表示编辑
const taskTitle = ref(null)
const dataForm = reactive({
    //新增表单数据
    form: {
        executors: [],  //执行人ID和姓名的数组
        files: [], //录音图片地址
        taskInfo: {
            id: undefined,
            title: undefined,
            createName: undefined,
            content: undefined, //任务描述
            classify: undefined,
            priority: undefined,
            reminderTime: undefined,  //时间提醒
            deadline: undefined,
            state: 0, //任务状态 0待办 1已办 2超期未完成
            imageUrl: [],  //图片地址
            recordUrl: [],  //录音地址
        }
    },

    options: [],
    cascadeData: [], //群组编辑默认数据
    imageUrl: [], //图片默认地址
    recordUrl: [] //录音默认地址
})

const options1 = [
    {
        value01: 0,
        label: "待办",
    },
    {
        value01: 1,
        label: "已办",
    },
    {
        value01: 2,
        label: "超期未完成",
    },
];
const options2 = [
    {
        value02: "0",
        label: "前期工作",
    },
    {
        value02: "1",
        label: "质量安全",
    },
    {
        value02: "2",
        label: "综合管理",
    },
    {
        value02: "3",
        label: "上级交办",
    },
    {
        value02: "4",
        label: "对外协调",
    },
    {
        value02: "5",
        label: "对上汇报",
    },
];
const options3 = [
    {
        value03: 0,
        label: "紧急事务(1级)",
    },
    {
        value03: 1,
        label: "一般事务(2级)",
    },
    {
        value03: 2,
        label: "待办事务(3级)",
    },
];

const tableTitle = [
    {
        props: "id",
        label: "任务编号",
        width: '',
    },
    {
        props: "title",
        label: "任务标题",
    },
    {
        props: "classify",
        label: "工作分类",
    },
    {
        props: "priority",
        label: "优先级",
    },
    {
        props: "createName",
        label: "创建人",
    },
    {
        props: "executors",
        label: "执行人",
    },
    {
        props: "deadline",
        label: "截止日期",
    },
    {
        props: "state",
        label: "状态",
    },
];

//获取code
// let code = getQueryString("code")

const tableData = ref()


//获取任务列表的数据进行刷新列表
const getList = () => {
    getTask({ params: Object.assign(seaForm, pageData) }).then((data) => {
        console.log('res1', data.data)
        if (data.data.code == 200) {
            tableData.value = retableDataL(data.data.data.records)
            tableData.value.map(item => {
                item.executors = item.executors.length > 1 ? item.executors[0] + '等' : item.executors;
            });
            total.value = data.data.data.pages
            getCascade().then((res) => {
                dataForm.options = regroupData(res)
            })
        }
    })
}


//搜索列表的查询
const onSubmit = () => {
    if (seaForm.time_range) {
        seaForm.time_range = seaForm.time_range.join()
    }
    getList()
}


//搜索重置
const onReset = () => {
    seaForm.time_range = undefined
    seaForm.executed = undefined
    seaForm.title = undefined
    seaForm.priority = undefined
    seaForm.state = undefined
    seaForm.classify = undefined
    getList()
}

//查看
const handleDetail = (row) => {
    const taskObj = JSON.parse(JSON.stringify(row))
    taskDetail(row.id).then((res) => {
        taskObj.executors = res.data.data.executors.map(item => {
            return item.empName
        })
        taskObj.executors = row.executors.map(item => {
            item = item + `(${row.state})`
            return item
        })
    });
    // if (row.images.length == 0) {
    //     row.images = [{ imageUrl: null }]
    // }
    //当images里没数据的时候，塞一个空数组，数组里放一个对象{imageUrl:null}
    let data = []
    const detForm = detailEcho(taskObj)
    detForm.images.forEach(e => {
        data.push(e.url)
        console.log(Object.values(data), 'adadadadad')
    })
    // detForm.srcList = Object.values(data)
    detForm.srcList = data
    store.upDetail(detForm)
    //跳转到任务中心
    router.push({
        path: '/details',
        params: { id: row.id }
    })
}

//编辑
const handleEdit = (row) => {
    taskTitle.value = "编辑任务"
    modalTypes.value = true
    dialogOpen.value = true
    taskDetail(row.id).then(({ data }) => {
        if (data.code == 200) {
            dataForm.form = detailEcho(data.data)
            dataForm.form = taskEdit(JSON.parse(JSON.stringify(dataForm.form)))
        }
        dataForm.form.executors.forEach(item => {
            dataForm.cascadeData.push(item.empId)
        })
        dataForm.imageUrl = dataForm.form.taskInfo.imageUrl
        dataForm.recordUrl = dataForm.form.taskInfo.recordUrl
        console.log(dataForm, 'dataForm')
    });

}

//删除
const handleDelete = (row) => {
    ElMessageBox.confirm("你确定删除吗?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            delTask(row.id).then((res) => {
                if (res.data.code != 200) {
                    ElMessage({
                        message: '删除失败',
                        type: 'error',
                    })
                } else {
                    getList()
                }
            })
        })
        .catch(() => {
        });
}

//分页
const handlePage = (val) => {
    pageData.start_number = val //更新页码
    getList()
}

//重置
function taskRuleFormRest() {
    dataForm.form.taskInfo.id = undefined;
    dataForm.form.taskInfo.title = undefined;
    dataForm.form.taskInfo.createName = undefined;
    dataForm.form.taskInfo.content = undefined;
    dataForm.form.taskInfo.classify = undefined;
    dataForm.form.taskInfo.priority = undefined;
    dataForm.form.taskInfo.reminderTime = undefined;
    dataForm.form.taskInfo.deadline = undefined;
    dataForm.form.taskInfo.state = 0;
    dataForm.form.taskInfo.imageUrl = [];
    dataForm.form.taskInfo.recordUrl = [];

    dataForm.form.files = [];
    dataForm.form.executors = [];

    dataForm.cascadeData = []
    dataForm.imageUrl = []
    dataForm.recordUrl = []
    nodeData.value = undefined;
}

//新增
const handleAdd = () => {
    dialogOpen.value = true
    modalTypes.value = false // true表示编辑的浮窗 false表示新增
    taskTitle.value = '新增任务'
}

const submitClose = () => {
    taskRuleFormRest()

    dialogOpen.value = false
    modalTypes.value = false
}


//重置表单
const resetForm = (formEl) => {
    taskRuleFormRest()
    // groupData.value.options = [];
    modalTypes.value = false
    dialogOpen.value = false
}

//提交用户表单
const submitSure = (formRef) => {
    if (!formRef) return
    formRef.validate((valid) => {
        console.log('form', dataForm.form)
        if (valid) {
            //后续对表单数据的处理
            if (dataForm.form.taskInfo.imageUrl.length != 0) {
                dataForm.form.files = dataForm.form.taskInfo.imageUrl.map(item => {
                    return item
                })
            }
            if (dataForm.form.taskInfo.recordUrl.length != 0) {
                dataForm.form.files.push(dataForm.form.taskInfo.recordUrl[0])
            }
            if (modalTypes.value == false) {
                nodeData.value.forEach(e => {
                    dataForm.form.executors.push({
                        empId: `${e.data.value}`,
                        empName: `${e.data.label}`,
                    })
                })
                //新增数据时
                addTask(dataForm.form).then((res) => {
                    taskRuleFormRest()
                    //关闭弹窗
                    dialogOpen.value = false;
                    ElMessage.closeAll();
                    if (res.data.code != 200) {
                        ElMessage({
                            message: '添加失败',
                            type: 'error',
                        })
                    } else {
                        ElMessage({
                            message: '添加成功',
                            type: 'success',
                        })
                        getList()
                    }
                })
            } else {
                editTask(dataForm.form).then((res) => {
                    taskRuleFormRest()
                    //关闭弹窗
                    dialogOpen.value = false;
                    ElMessage.closeAll();
                    if (res.data.code != 200) {
                        ElMessage({
                            message: '更新失败',
                            type: 'error',
                        })
                    } else {
                        ElMessage({
                            message: '更新成功',
                            type: 'success',
                        })
                        getList()
                    }
                })
            }
        }
    }
    )
}

//群组节点
let nodeData = ref([])
//节点改变后拿到节点数据
const changeAcademic = (cascaderRef) => {
    nodeData.value = cascaderRef.getCheckedNodes()
    nodeData.value = nodeData.value.filter(item => {
        return item.level != 1
    })
}

//对任务列表格式进行处理
const retableDataL = (val) => {
    const tableDataL = val
    let data = []
    if (tableDataL.length !== 0 && tableDataL !== undefined) {
        tableDataL.forEach((e) => {
            let pushData = {} //任务信息
            let executors = [] //执行人信息
            pushData = { ...e.taskInfo }
            pushData.files = e.files
            pushData.images = e.images
            switch (pushData.classify) {
                case '0':
                    pushData.classify = '前期工作'
                    break;
                case '1':
                    pushData.classify = '质量安全'
                    break;
                case '2':
                    pushData.classify = '综合管理'
                    break;
                case '3':
                    pushData.classify = '上级交办'
                    break;
                case '4':
                    pushData.classify = '对外协调'
                    break;
                case '5':
                    pushData.classify = '对上汇报'
                    break;
            }
            switch (pushData.state) {
                case 0:
                    pushData.state = '待办'
                    break;
                case 1:
                    pushData.state = '已办'
                    break;
                case 2:
                    pushData.state = '超期未完成'
                    break;
            }
            switch (pushData.priority) {
                case '0':
                    pushData.priority = '紧急事务(1级)'
                    break;
                case '1':
                    pushData.priority = '一般事务(2级)'
                    break;
                case '2':
                    pushData.priority = '待办事务(3级)'
                    break;
            }
            e.executors.forEach((item => {
                executors.push(item['empName'])
            }))
            pushData.executors = executors
            data.push(pushData)
        })
    }
    return data
}



//任务数据编辑处理
const taskEdit = (val) => {
    const form = {
        executors: val.executors,  //执行人ID和姓名的数组
        files: [], //录音图片地址
        taskInfo: {
            id: val.taskInfo.id,
            title: val.taskInfo.title,
            createName: val.taskInfo.createName,
            content: val.taskInfo.content, //任务描述
            classify: val.taskInfo.classify,
            priority: val.taskInfo.priority,
            reminderTime: val.taskInfo.reminderTime,  //时间提醒
            deadline: val.taskInfo.deadline,
            state: 0, //任务状态 0待办 1已办 2超期未完成
            imageUrl: val.images,  //图片地址
            recordUrl: val.files,  //录音地址
        }
    }
    // console.log(form, 'val');
    switch (val.taskInfo.priority) {
        case '紧急事务(1级)':
            form.taskInfo.priority = '0'
            break;
        case '一般事务(2级)':
            form.taskInfo.priority = '1'
            break;
        case '待办事务(3级)':
            form.taskInfo.priority = '2'
            break;
    }
    switch (val.taskInfo.state) {
        case '待办':
            form.taskInfo.state = 0
            break;
        case '已办':
            form.taskInfo.state = 1
            break;
        case '超期未完成':
            form.taskInfo.state = 2
            break;
    }
    switch (val.taskInfo.classify) {
        case '前期工作':
            form.taskInfo.classify = '0'
            break;
        case '质量安全':
            form.taskInfo.classify = '1'
            break;
        case '综合管理':
            form.taskInfo.classify = '2'
            break;
        case '上级交办':
            form.taskInfo.classify = '3'
            break;
        case '对外协调4':
            form.taskInfo.classify = '4'
            break;
        case '对上汇报':
            form.taskInfo.classify = '5'
            break;
    }

    return form
}

//查看回显
const detailEcho = (val) => {
    console.log(val, 'aaaaa')
    let data1 = []
    let data2 = []
    val.files.forEach(e => {
        let obj = {}
        obj.ext = e.fileName
            .substring(e.fileName.lastIndexOf(".") + 1)
            .toLowerCase();
        obj.size = e.fileSize
        obj.name = e.fileName
        obj.url = `${e.fileUrl}` + `${e.fileName}`
        obj.url = obj.url.replace(undefined, '')
        data1.push(obj)
    })
    val.images.forEach(e => {
        let obj = {}
        obj.ext = e.imageName
            .substring(e.imageName.lastIndexOf(".") + 1)
            .toLowerCase();
        obj.size = e.imageSize
        obj.name = e.imageName
        obj.url = `${e.imageUrl}` + `${e.imageName}`
        obj.url = obj.url.replace(undefined, '')
        data2.push(obj)
    })
    val.files.splice(0, val.files.length)
    val.images.splice(0, val.images.length)
    val.files = data1
    val.images = data2
    return val
}

onMounted(() => {
    setTimeout(() => {
        getList()
    }, 300)
    // getList()
})

</script>
<style lang="less" scoped>
.el-card {
    margin-top: 10px;
}

:deep(.el-card__body) {
    padding: 10px;
}

.el-form {
    .el-form-item {
        display: flex;
        align-items: baseline;
    }
}

.el-input,
.el-select {
    width: 180px;
}

span {
    font-size: 16px;
    margin-left: 20px;
}

.right {
    float: right;
    padding-right: 20px;
}

.right .search,
.add {
    color: #ffffff;
    background-color: #fd8c71;
    border: none;
    margin: 5px;
}

.right .reset {
    background-color: #fda671;
    border: none;
}

.el-button:hover {
    opacity: 0.7;
}

.el-table {
    font-size: 12px;
    --el-table-header-bg-color: #dadada9d;
}

:deep(.el-table .cell) {
    text-align: center;
}

.el-link {
    font-size: 12px;
    font-family: Arial;
    padding-right: 15px;
}

// .main-top {
//   height: 20vh;
// }

.common-table {

    position: relative;
    margin-top: 20px;

    .pager {
        display: flex;
        flex-direction: row-reverse;
        // position: absolute;
        // right: -5px;
        // top: 50vh;
    }
}

.main-middle {
    margin-bottom: -10px;
}
</style>